package com.yang;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 当前解码器优先级高于HTTP和MQTT 这里跟加入 管道的顺序有关，最好置于其他管道之上
 */
public class IotDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        in.markReaderIndex();
        byte[] head = new byte[2];
        in.readBytes(head);
        System.err.println("111111");
        byte[] len = new byte[2];
        in.readBytes(len);
        int integer = convertToInteger(len);
        if (integer <0 || in.readableBytes() < integer + 23) {
            System.err.println(integer);
            System.err.println(in.readableBytes());
            in.resetReaderIndex();
            System.err.println("1111112");

            return;
        }
        byte[] data = new byte[integer + 23];
        in.readBytes(data);
        byte[] allData = new byte[integer + 27];
        System.arraycopy(head, 0, allData, 0, 2);
        System.arraycopy(len, 0, allData, 2, 2);
        System.arraycopy(data, 0, allData, 4, integer + 23);
        String s = bytesToHex(allData);
        System.err.println(s);
        out.add(allData);

    }

    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex+" ");
        }
        return sb.toString();
    }
    public static int convertToInteger(byte[] byteArray) {
        int result = 0;

        result = ((byteArray[1] << 8) & 0xFF00) | (byteArray[0] & 0xFF);

        return result;
    }

    public static void main(String[] args) {
        byte[] len = new byte[2];
        len[0] = 0X04;
        len[1] = 0X00;
        int i = convertToInteger(len);
        System.err.println(i);
    }
}
